package com.pb.b2b.bean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.pb.b2b.model.Mark;
import com.pb.b2b.service.MarkService;
import com.pb.b2b.util.FacesUtils;

@Component
@Scope("view")
@ManagedBean(name = "createMarkBean")
public class CreateMarkBean extends BaseBean {

	@Autowired
	MarkService markService;

	private String name;
	private String logo;
	private final String TEMP_DIR = "temporary";
	private final String UPLOAD_DIR = "upload";
	private UploadedFile file;

	private String tempFileDir;
	private String fileDir;
	private String fileName;

	private String strFileName;
	private String strBaseFileName;
	private String strFileNameExt;

	@PostConstruct
	public void init() {

	}

	/* METHOD */
	@Override
	public String confirmAction() {
		if (StringUtils.isEmpty(name)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR, "ERROR_MARK_NAME_CAN_NOT_EMPTY");
			return RETURN_ERROR;
		}

		if (file == null) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR, "ERROR_MARK_LOGO_CAN_NOT_EMPTY");
			return RETURN_ERROR;
		}

		if (getFileSizeByte(file) == 0) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR, "ERROR_MARK_LOGO_CAN_NOT_EMPTY");
			return RETURN_ERROR;
		}

		initFileName(file);

		DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy");
		DateTime dateTime = new DateTime();
		String sysPath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();

		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		sysPath = externalContext.getRealPath("//WEB-INF//files//");
		fileDir = sysPath + File.separator + "resources" + File.separator + "upload" + File.separator + "logo"
				+ File.separator;
		tempFileDir = sysPath + File.separator + TEMP_DIR + File.separator;

		tempFileDir = "/b2b/upload/temp/";
		fileDir = "/b2b/upload/logo/";

		tempFileDelete(tempFileDir);

		String[] extentions = { "jpg", "png", "gif", "jpeg" };

		if (!checkFileExtension(strFileNameExt, extentions)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR, "ERROR_DOSYA_UZANTI_HATA");
			return RETURN_ERROR;
		}

		DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("MMddHHmmssSSS");
		fileName = strBaseFileName + "_" + dateTime.toString(timeFormatter) + "." + strFileNameExt;

		// Dosya Upload
		if (!upload(file, tempFileDir, fileName)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR, "ERROR_RESIM_YUKLEMEDE_HATA");
			return RETURN_ERROR;
		}
		logo = tempFileDir + fileName;

		return RETURN_SUCCESS;
	}

	@Override
	public String executeAction() {

		// hata yok ise temp dir den gerçek dir e taşı
		copyFile(tempFileDir, fileDir, fileName);

		Mark mark = new Mark();
		mark.setName(name);
		mark.setLogo(fileDir + fileName);
		markService.createMark(mark);
		if (hasError()) {
			return RETURN_ERROR;
		}
		return RETURN_SUCCESS;
	}

	/**
	 * Resim yukleme islemi yapar <br/>
	 * 
	 * 
	 * @param file
	 * @param fileDir
	 * @param fileName
	 * @return yuklenen dosyanin yolunu geri doner null ise yuklenememistir
	 */
	public boolean upload(UploadedFile file, String fileDir, String fileName) {
		boolean control = false;
		if (file != null) {
			// String fileName = reNameFile(file.getFileName());
			control = true;
			OutputStream out = null;
			InputStream in = null;

			// Do what you want with the file
			try {
				// copyFile(destination, file.getInputstream());

				File f = new File(fileDir);
				boolean exists = f.exists();
				if (!exists) {
					// Create file if it does not exist
					boolean success = f.mkdirs();
					// TODO : kontrol eklenecek mi?
					// if (success) {
					// System.out.println("File created");
					// } else {
					// System.out.println("File already exists");
					// }
				}

				// write the inputStream to a FileOutputStream
				out = new FileOutputStream(new File(fileDir + fileName));

				int read = 0;
				byte[] bytes = new byte[1024];
				in = file.getInputstream();

				while ((read = in.read(bytes)) != -1) {
					out.write(bytes, 0, read);
				}

				// System.out.println("New file created!");
			} catch (IOException e) {
				control = false;
				e.printStackTrace();
			} finally {
				try {
					if (in != null) {
						in.close();
					}
					if (out != null) {
						out.flush();
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return control;
	}

	public void copyFile(String tempFileDir, String fileDir, String fileName) {
		InputStream in = null;
		OutputStream out = null;
		try {
			File tempFile = new File(tempFileDir + fileName);
			File file = new File(fileDir + fileName);

			File f = new File(fileDir);
			boolean exists = f.exists();
			if (!exists) {
				// Create file if it does not exist
				boolean success = f.mkdirs();
				// TODO : kontrol eklenecek mi?
				// if (success) {
				// System.out.println("File created");
				// } else {
				// System.out.println("File already exists");
				// }
			}

			in = new FileInputStream(tempFile);
			out = new FileOutputStream(file);

			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}

			// System.out.println("newFile is copied successful!");

			in.close();
			in.close();

			// delete the original file
			tempFile.delete();
			// if (tempFile.delete())
			// System.out.println("sourceFile is deleted successful!");

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void tempFileDelete(String strFileDir) {
		File fileDir = new File(strFileDir);
		if (fileDir.isDirectory()) {
			File[] uploadedFiles = fileDir.listFiles();
			for (File uploadedFile : uploadedFiles) {
				if (uploadedFile.isFile()) {
					uploadedFile.delete();
				}
			}
		}
	}

	/**
	 * Gonderilen dosya ismi ve dosya uzanti listesine göre kontrol yapar.<br/>
	 * Dosya uzanti listesinde olmayan bir uzantiya sahip dosya ise false doner. <br/>
	 * 
	 * Orn1 : "deneme.txd", ["jpg", "png"] -> false <br/>
	 * Orn2 : "deneme.jpg", ["jpg", "png"] -> true <br/>
	 * 
	 * @param fileName
	 * @param extensions
	 * @return
	 * @throws IndexOutOfBoundsException
	 *             : uzantısız dosya
	 */
	public boolean checkFileExtension(String fileExtension, String[] extensions) {
		boolean exist = false;
		try {
			for (String extension : extensions) {
				if (extension.compareToIgnoreCase(fileExtension) == 0) {
					exist = true;
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return exist;
	}

	public double getFileSizeByte(UploadedFile file) {
		double bytes = -1;
		if (file != null) {
			bytes = file.getSize();
		}
		return bytes;
	}

	private void initFileName(UploadedFile file) {
		setStrFileName(FilenameUtils.getName(file.getFileName()));
		setStrBaseFileName(FilenameUtils.getBaseName(file.getFileName()));
		setStrFileNameExt(FilenameUtils.getExtension(file.getFileName()));
	}

	public String getStatusText(boolean value) {
		String bundleName = "resources.application";
		String tmp = FacesUtils.getResourceBundleString(bundleName, "lbl_status_" + (value ? "1" : "0"), null);
		return tmp;
	}

	/* GETTER - SETTER */
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public MarkService getMarkService() {
		return markService;
	}

	public void setMarkService(MarkService markService) {
		this.markService = markService;
	}

	public UploadedFile getFile() {
		return file;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}

	public String getStrFileName() {
		return strFileName;
	}

	public void setStrFileName(String strFileName) {
		this.strFileName = strFileName;
	}

	public String getStrBaseFileName() {
		return strBaseFileName;
	}

	public void setStrBaseFileName(String strBaseFileName) {
		this.strBaseFileName = strBaseFileName;
	}

	public String getStrFileNameExt() {
		return strFileNameExt;
	}

	public void setStrFileNameExt(String strFileNameExt) {
		this.strFileNameExt = strFileNameExt;
	}

	public final String getLogo() {
		return logo;
	}

	public final void setLogo(String logo) {
		this.logo = logo;
	}

}
